<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use app\admin\model\UserCustomers;
use think\Config;
use think\Validate;
use think\Db;

class StudentClassService
{
    const STATUS_KIDS = 'kids';

    // 列表
    public static function index($data)
    {
        if (!isset($data['studios_id']) || !is_numeric($data['studios_id']) || intval($data['studios_id']) <= 0) {
            return ['code' => 400, 'msg' => 'Missing or invalid studios_id parameter', 'state' => 'ERROR'];
        }

        $limit = min(max(intval($data['limit'] ?? 10), 1), 100); // 限制 limit 范围 [1, 100]

        try {
            // 基础查询
            $studio = \app\admin\model\Classes::where('studios_id', intval($data['studios_id']))
                ->field('class_id,class_name,studios_id,level_id,capacity')
                ->order('class_id', 'desc')
                ->paginate($limit);

            $items = $studio->items();

            if (empty($items)) {
                return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $studio];
            }

            // 提取ID列表
            $studioIds = array_column($items, 'studios_id');
            $levelIds = array_column($items, 'level_id');

            // 查询 studio 信息
            $studioList = \app\admin\model\Studios::whereIn('id', $studioIds)
                ->field('id as studio_id,studio_name')
                ->select();
            $studios = array_column($studioList, null, 'studio_id');

            // 查询 level 信息（包含 category_id）
            $levelList = \app\admin\model\StudentCourseLevel::whereIn('level_id', $levelIds)
                ->field('level_id,level_name,category_id')
                ->select();
            $levels = array_column($levelList, null, 'level_id');

            // 提取 category_id 并查询
            $categoryIds = array_column($levelList, 'category_id');
            $categoryList = \app\admin\model\StudentCourseCategory::whereIn('category_id', $categoryIds)
                ->field('category_id,category_name')
                ->select();
            $categories = array_column($categoryList, null, 'category_id');

            // 合并数据
            $studio->each(function (&$item) use ($studios, $levels, $categories) {
                $studioInfo = $studios[$item['studios_id']] ?? [];
                $item['studio_id'] = $studioInfo['studio_id'] ?? '';
                $item['studio_name'] = $studioInfo['studio_name'] ?? '';

                $levelInfo = $levels[$item['level_id']] ?? [];
                $item['level_name'] = $levelInfo['level_name'] ?? '';

                $categoryId = $levelInfo['category_id'] ?? null;
                $item['category_name'] = $categoryId ? ($categories[$categoryId]['category_name'] ?? '') : '';
            });

            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $studio];
        } catch (\think\Exception\DbException $e) {
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'ERROR'];
        }
    }


    // 添加
    public static function add($data)
    {
        // 验证规则
        $validate = new Validate([
            'studios_id' => 'require',
            'class_name' => 'require',
            'level_id' => 'require',
            'capacity' => 'require',
            'student_ids' => 'require'
        ], [
            'studio_id.require' => 'studios is not empty', // 注意 studio_id 与 studios_id 不一致
            'class_name.require' => 'Class Name is not empty',
            'level_id.require' => 'LevelId is not empty',
            'capacity.require' => 'Capacity is not empty',
            'student_ids.require' => 'Student is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        $student_ids = explode(',', $data['student_ids']);

        // 校验 student_id 是否为有效整数
        foreach ($student_ids as $id) {
            if (!is_numeric($id) || intval($id) <= 0) {
                return ['code'=>400, 'msg'=>'Invalid Student ID format', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
            }
        }

        if(count($student_ids) > $data['capacity']) {
            return ['code'=>400, 'msg'=>'Capacity is not enough', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {
            Db::startTrans();

            $class = \app\admin\model\Classes::create([
                'studios_id'        =>  $data['studios_id'],
                'class_name'        =>  $data['class_name'],
                'level_id'          =>  $data['level_id'],
                'capacity'          =>  $data['capacity'],
                'createtime'       =>  time(),
                'updatetime'       =>  time(),
            ]);

            $studentClassData = [];
            foreach ($student_ids as $student_id){
                $studentClassData[] = [
                    'studio_id'       =>  $data['studios_id'],
                    'class_id'        =>  $class->class_id,
                    'student_id'      =>  $student_id,
                    'createtime'      =>  time(),
                    'updatetime'      =>  time(),
                ];
            }

            $result = \app\admin\model\StudentClass::insertAll($studentClassData);

            if(!$result){
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }

            Db::commit();
            return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$class];

        } catch (\Exception $e) {
            Db::rollback();
            // 可选：记录日志
            // Log::error('Database error: ' . $e->getMessage());
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    // 编辑
    public static function edit($data)
    {
        $validate = new Validate([
            'class_id' => 'require',
            'studios_id' => 'require',
            'class_name' => 'require',
            'level_id' => 'require',
            'capacity' => 'require',
            'student_ids' => 'require'
        ], [
            'class_id.require' => 'Class Id is not empty',
            'studio_id.require' => 'Studios is not empty',
            'class_name.require' => 'Class Name is not empty',
            'level_id.require' => 'LevelId is not empty',
            'capacity.require' => 'Capacity is not empty',
            'student_ids.require' => 'Student is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 校验 capacity 是否为整数
        if (!is_numeric($data['capacity']) || intval($data['capacity']) <= 0) {
            return ['code'=>400, 'msg'=>'Capacity must be a positive integer', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 解析学生ID列表
        $student_ids = array_filter(array_map('trim', explode(',', $data['student_ids'])), 'is_numeric');
        if (count($student_ids) > $data['capacity']) {
            return ['code'=>400, 'msg'=>'Capacity is not enough', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        Db::startTrans(); // 显式开启事务
        try {
            // 更新班级信息（注意不要更新 createtime）
            $class = \app\admin\model\Classes::where(['class_id'=>$data['class_id']])->update([
                'studios_id'        =>  $data['studios_id'],
                'class_name'        =>  $data['class_name'],
                'level_id'          =>  $data['level_id'],
                'capacity'          =>  $data['capacity'],
                'updatetime'        =>  time(),
            ]);

            // 删除旧的学生关联
            \app\admin\model\StudentClass::where(['class_id'=>$data['class_id']])->delete();

            // 构造要插入的数据
            $insertData = [];
            foreach ($student_ids as $student_id){
                $insertData[] = [
                    'studio_id'       =>  $data['studios_id'],
                    'class_id'        =>  $data['class_id'],
                    'student_id'      =>  $student_id,
                    'createtime'      =>  time(),
                    'updatetime'      =>  time(),
                ];
            }

            // 批量插入
            $result = \app\admin\model\StudentClass::insertAll($insertData);
            if(!$result){
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }

            Db::commit();
            return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$class];

        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();

        // 验证参数
        if (empty($data['class_id']) || !is_numeric($data['class_id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 开启事务
        Db::startTrans();
        try {
            // 删除学生关联数据
            $deletedStudents = \app\admin\model\StudentClass::where(['class_id' => $data['class_id']])->delete();
            // 删除班级
            $deletedClass = \app\admin\model\Classes::destroy($data['class_id']);

            if ($deletedStudents && $deletedClass) {
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>null];
            } else {
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        } catch (\Exception $e) {
            Db::rollback();
            // 记录日志
            \think\facade\Log::error('Delete class error: ' . $e->getMessage());
            return ['code' => 400, 'msg' => 'Database error occurred', 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }


    // 下拉学生
    public static function select_student($data)
    {
        // 输入校验
        if (!isset($data['keyword']) || !is_string($data['keyword'])) {
            return ['code' => 400, 'msg' => 'Invalid keyword', 'state' => 'ERROR', 'data' => []];
        }

        // 构建查询条件
        $where['status'] = ['in', [self::STATUS_KIDS]];
        $keyword = trim($data['keyword']);
        if (!empty($keyword)) {
            $where['surname|given_name|english_name'] = ['like', '%'.$data['keyword'].'%'];
        }
        
        // 执行查询
        try {
            $studio = UserCustomers::where($where)->order('id', 'desc')->select();
        } catch (\Exception $e) {
            // 日志记录：$e->getMessage()
            return ['code' => 500, 'msg' => 'Database error', 'state' => 'ERROR', 'data' => []];
        }

        return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $studio];
    }



    // 下拉查询
    public static function select($data)
    {
        // 验证输入参数
        if (!isset($data['studios_id']) || empty($data['studios_id'])) {
            return self::error('Missing or invalid studios_id', 400);
        }

        try {
            $list = \app\admin\model\Classes::where(['studios_id' => $data['studios_id']])
                ->field(['class_id', 'class_name'])
                ->order('class_id', 'desc')
                ->select();

            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $list];
        } catch (\Exception $e) {
            // 记录日志（可选）
            // Log::error($e->getMessage());

            return ['code' => 400, 'msg' => 'Database query failed', 'state' => 'Error', 'data' => null];
        }
    }


}
